<?php
/**
 * Create by 11li
 * Date 2020/1/15
 * Time 15:44
 *
 */

namespace app\common\service;


use app\common\model\AgentAdmin;
use app\common\model\AgentSendTips;
use app\common\model\AgentShop;
use app\common\model\Goods;
use app\common\model\GoodsSpec;
use app\common\model\PostMan;
use app\common\model\ShipOrder;
use think\Db;

class ShipService extends Server
{
	/**
	 * 获取发货的用户归属代理
	 * @param $userId
	 * @return bool
	 * @throws \think\exception\DbException
	 */
	public static function getAgentId($userId) {
		$agent = AgentShop::get(['user_id' => $userId]);
		
		if($agent) {
			//如果是代理且状态正常返回代理ID
			return $agent['status'] == AgentShop::STATUS_Y ? $agent['id'] : false;
		}
		
		//查找是否管理员
		$admin = AgentAdmin::get(['user_id' => $userId, 'status' => AgentAdmin::STATUS_NORMAL]);
		if($admin) {
			return $admin['agent_id'];
		}
		
		//查找是否配送员
		$postman = PostMan::get(['user_id' => $userId, 'status' => PostMan::STATUS_NORMAL]);
		if($postman) {
			return $postman['agent_id'];
		}
		
		return false;
	}
	
	/**
	 * 获取代理发货提醒列表
	 * @param $userId
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getSendList($userId) {
		$rows = Db::name('agentSendTips')->alias('t')
			->join('agentShop a', 't.agent_id = a.id', 'left')
			->join('goods g', 't.goods_id = g.id', 'left')
			->join('goodsSpec s', 't.spec_id = s.id', 'left')
			->join('area p', 'a.provice_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where(['t.user_id' => $userId, 't.status' => AgentSendTips::STATUS_WAIT])
			->field('t.id, t.agent_id, t.goods_id, t.spec_id, a.name as agent_name, a.image as agent_image, a.lat, a.lng, a.address, a.mobile, p.name as province_name, c.name as city_name, aa.name as area_name, g.name as goods_name, s.name as spec_name')
			->order(['t.create_time' => 'asc'])
			->select();
		
		$list = [];
		if($rows) {
			foreach ($rows as $row) {
				$key = $row['agent_id'];
				if(!isset($list[$key])) {
					$list[$key] = [
						'agent_id' => $key,
						'agent_name' => $row['agent_name'],
						'agent_image' => $row['agent_image'],
						'lat' => $row['lat'],
						'lng' => $row['lng'],
						'address' => $row['province_name'].$row['city_name'].$row['area_name'].$row['address'],
						'goods_list' => []
					];
				}
				
				$list[$key]['goods_list'][] = [
					'name' => ($row['spec_name'] ? : '').$row['goods_name'],
					'goods_id' => $row['goods_id'],
					'spec_id' => $row['spec_id']
				];
			}
		}
		
		return array_values($list);
	}
	
	
	/**
	 * 获取代理发货记录
	 * @param $agentId
	 * @param $page
	 * @param $status
	 * @param string $postmanId
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getShipRecord($agentId, $page, $status, $postmanId = '') {
		$where = [
			'o.send_agent_id' => $agentId,
			'o.status' => $status
		];
		
		$postmanId && $where['o.postman_id'] = $postmanId;
		
		$model = Db::name('shipOrder')->alias('o');
		
		$total = $model->where($where)->count();
		
		$orders = Db::name('shipOrder')->alias('o')
			->join('agentShop a', 'o.sign_agent_id = a.id', 'left')
			->join('postMan p', 'o.postman_id = p.id', 'left')
			->join('area pp', 'a.provice_id = pp.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where($where)
			->page($page)
			->field('o.id, o.sign_agent_id, a.name as agent_name, a.image as agent_image, a.lat, a.lng, a.address, a.mobile, pp.name as province_name, c.name as city_name, aa.name as area_name,  o.postman_id, p.name as postman_name, o.shipping_name, o.shipping_no, o.status, from_unixtime(o.create_time) as date, o.send_code, o.sign_code, o.destory_number')
			->order(['o.create_time' => 'desc'])
			->select();
		
		if($orders) {
			$statusList = ShipOrder::$statusList;
			foreach ($orders as &$order) {
				$order['status_text'] = $statusList[$order['status']] ??'';
				$order['address'] = $order['province_name'].$order['city_name'].$order['area_name'].$order['address'];
				$order['goods_list'] = Db::name('shipItem')->alias('i')
					->join('goods g', 'i.goods_id = g.id', 'left')
					->join('goodsSpec s', 'i.spec_id = s.id', 'left')
					->where(['i.order_id' => $order['id']])
					->field('i.*, g.name as goods_name, s.name as spec_name')
					->select();
			}
		}
		
		return [
			'total' => $total,
			'list' => $orders
		];
	}
	
	/**
	 * 获取代理签收记录
	 * @param $agentId
	 * @param $page
	 * @param $status
	 * @return array
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getShipInRecord($agentId, $page, $status) {
		$where = [
			'o.sign_agent_id' => $agentId,
			'o.status' => $status
		];
		
		$model = Db::name('shipOrder')->alias('o');
		
		$total = $model->where($where)->count();
		
		$orders = Db::name('shipOrder')->alias('o')
			->join('agentShop a', 'o.sign_agent_id = a.id', 'left')
			->join('postMan p', 'o.postman_id = p.id', 'left')
			->where($where)
			->page($page)
			->field('o.id, o.sign_agent_id, a.name as agent_name, a.image as agent_image, a.lat, a.lng, a.address, a.mobile, o.postman_id, p.name as postman_name, o.shipping_name, o.shipping_no, o.status, from_unixtime(o.create_time) as date, o.send_code, o.sign_code, o.destory_number')
			->order(['o.create_time' => 'desc'])
			->select();
		
		if($orders) {
			$statusList = ShipOrder::$statusList;
			foreach ($orders as &$order) {
				$order['status_text'] = $statusList[$order['status']] ??'';
				$order['goods_list'] = Db::name('shipItem')->alias('i')
					->join('goods g', 'i.goods_id = g.id', 'left')
					->join('goodsSpec s', 'i.spec_id = s.id', 'left')
					->where(['i.order_id' => $order['id']])
					->field('i.*, g.name as goods_name, s.name as spec_name')
					->select();
			}
		}
		
		return [
			'total' => $total,
			'list' => $orders
		];
	}
	
	/**
	 * 获取在售商品及库存
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getSaleGoodsAndSpec() {
		$goods = Db::name('goods')
			->where(['status' => Goods::STATUS_SALE])
			->order(['sort' => 'asc'])
			->field('id as goods_id, name as goods_name')
			->select();
		
		if($goods) {
			foreach ($goods as &$item) {
				$specList = Db::name('goodsSpec')
					->where(['goods_id' => $item['goods_id'], 'status' => GoodsSpec::STATUS_Y])
					->field('id as spec_id, name as spec_name, 0 as number')
					->select();
				if(!$specList) {
					$item['spec'][] = [
						'spec_id' => 0,
						'spec_name' => '默认',
						'number' => 0
					];
				 } else {
					$item['spec'] = $specList;
				}
			}
		}
		
		return $goods ? : [];
	}
	
	/**
	 * 获取在售商品的代理库存
	 * @param array $goods
	 * @param $agentId
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getAgentGoodsStock(array $goods, $agentId)
	{
		foreach ($goods as &$good) {
			foreach ($good['spec'] as &$spec) {
				$stock = Db::name('agentStock')
					->where(['agent_shop_id' => $agentId, 'goods_id' => $good['goods_id'], 'spec_id' => $spec['spec_id']])
					->find();
				$spec['number'] = $stock ? $stock['number'] : 0;
			}
		}
		
		return $goods;
	}
	
	public function closeOrder($agentId, $orderId)
	{
		if($agentId === '' || !$orderId) {
			$this->errorMsg = '参数错误';
			return false;
		}
		
		$model = new ShipOrder();
		$order = $model->where([
			'id' => $orderId,
			'send_agent_id' => $agentId,
		])->find();
		
		if(!$order) {
			$this->errorMsg = '订单不存在';
			return false;
		}
		
		if(!in_array($order['status'], [$model::STATUS_WAIT, $model::STATUS_SHIPPING])) {
			$this->errorMsg = '该订单不可关闭';
			return false;
		}
		
		$res = $model->save(['status' => $model::STATUS_CLOST], ['id' => $orderId]);
		if(!$res) {
			$this->errorMsg = $model->getError();
			return false;
		}
		
		return true;
	}
}